<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
	<base href="${pageContext.request.contextPath}/">
<meta charset="UTF-8">

<link href="jquery/bootstrap_3.3.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
<link href="jquery/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css" type="text/css" rel="stylesheet" />
<link href="jquery/bs_pagination-master/css/jquery.bs_pagination.min.css" type="text/css" rel="stylesheet"/>

<script type="text/javascript" src="jquery/jquery-1.11.1-min.js"></script>
<script type="text/javascript" src="jquery/bootstrap_3.3.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="jquery/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.js"></script>
<script type="text/javascript" src="jquery/bootstrap-datetimepicker-master/locale/bootstrap-datetimepicker.zh-CN.js"></script>
<script type="text/javascript" src="jquery/bs_pagination-master/js/jquery.bs_pagination.min.js"></script>
<script type="text/javascript" src="jquery/bs_pagination-master/localization/en.js"></script>

<script type="text/javascript">

	$(function(){
		//给”创建“按钮添加单击事件
		$("#createActivityBtn").click(function (){
			//初始化工作，重置表单
			$("#createActivityForm")[0].reset();
			//弹出创建市场活动的模态窗口
			$("#createActivityModal").modal("show");
		});

		//日历插件
		$(".mydate").datetimepicker({
			language:'zh-CN', //设置语言
			autoclose:true, //自动关闭
			format:'yyyy-mm-dd', //日期格式
			minView:'month', //可选择的最小视图
			initialDate:new Date(), //初始化显示日期
			todayBtn:true, //是否显示”今天"按钮
			clearBtn:true //是否显示“清空”按钮
		});

		//给创建模态窗口“保存”按钮添加单击事件
		$("#saveCreateActivityBtn").click(function(){
			//收集参数
			let owner = $("#create-marketActivityOwner").val();
			let name = $.trim($("#create-marketActivityName").val());
			let startDate = $("#create-startDate").val();
			let endDate = $("#create-endDate").val();
			let cost = $.trim($("#create-cost").val());
			let description = $.trim($("#create-describe").val());

			//表单验证
			if(!formVerify(owner,name,startDate,endDate,cost)) {
				return;
			}

			//发送请求
			$.ajax({
				url:"workbench/activity/saveCreateActivity.do",
				data:{
					owner, name, startDate, endDate, cost, description,
				},
				type:"post",
				dataType:"json",
				success:function(data) {
					//创建成功
					if(data.code == "1") {
						//关闭模态窗口
						$("#createActivityModal").modal("hide");
						//刷新市场活动列，显示第一页数据，保持每页显示条数不变
						queryActivityByConditionForPage(1,$("#demo_page1").bs_pagination('getOption','rowsPerPage'));
					}
				}
			})
		});

		//当市场活动主页面加载完成，查询所有数据的第一页以及所有数据的总条数，默认每页显示10条；
		queryActivityByConditionForPage(1,5);

		//给“查询”按钮添加单击事件
		$("#queryActivityBtn").click(function (){
			//获取上一次显示列表的pageSize
			queryActivityByConditionForPage(1,$("#demo_page1").bs_pagination('getOption','rowsPerPage'));
		});

		//给“全选”按钮添加单击事件
		$("#checkAll").click(function(){
			//实现是否全选
			$("#tBody input[type='checkbox']").prop("checked",this.checked);
		});

		//给每一个checkbox添加单击事件
		$("#tBody").on("click","input[type='checkbox']",function(){
			//所有checkbox选中，则"全选"选中，否则，不选中；
			$("#checkAll").prop("checked",$("#tBody input[type='checkbox']").size() == $("#tBody input[type='checkbox']:checked").size());
		});

		//给”删除“按钮添加单击事件
		$("#deleteActivityBtn").click(function (){
			//获取所有选中的checkbox
			let checkBoxs = $("#tBody input[type='checkbox']:checked");
			//每次至少删除一条数据
			if(checkBoxs.size() < 1) {
				alert("至少选中一条数据进行删除！！！");
				return;
			}
			if (window.confirm("是否确认删除？")) {
				var ids="";
				//遍历选中标签，拼接id字符串（id=xxx&id=xxx&id=xxx）
				$.each(checkBoxs,function(){
					ids += "id=" + this.value + "&";
				});
				ids = ids.substring(0,ids.length-1);
				$.ajax({
					url:"workbench/activity/deleteActivityByIds.do",
					data:ids,
					type:"post",
					dataType:"json",
					success:function(data){
						if(data.code == 1) {
							//刷新市场活动列表,显示第一页数据,保持每页显示条数不变
							queryActivityByConditionForPage(1,$("#demo_page1").bs_pagination('getOption','rowsPerPage'));
						}else {
							//提示信息
							alert(data.message);
						}
					}
				});
			}
		});

		//给"修改“按钮添加单击事件
		$("#modifyActivityBtn").click(function (){
			//获取所有选中的checkbox
			let checkBoxs = $("#tBody input[type='checkbox']:checked");
			if(checkBoxs.size() != 1) {
				alert("只能选中一条数据进行修改！！！");
				return;
			}
			let id = checkBoxs[0].value;
			$.ajax({
				url:"workbench/activity/queryActivityById.do",
				data:{id},
				type:"post",
				dataType:"json",
				success:function(data){
					//把市场活动的信息显示在修改的模态窗口上
					$("#edit-id").val(data.id);
					$("#edit-marketActivityOwner").val(data.owner);
					$("#edit-marketActivityName").val(data.name);
					$("#edit-startDate").val(data.startDate);
					$("#edit-endDate").val(data.endDate);
					$("#edit-cost").val(data.cost);
					$("#edit-description").val(data.description);
					//显示模态窗口
					$("#editActivityModal").modal("show");
				}
			});
		});

		//给修改模态窗口“更新"按钮添加单击事件
		$("#updateActivityBtn").click(function(){
			//获取参数
			var id = $("#edit-id").val();
			var owner = $("#edit-marketActivityOwner").val();
			var name = $("#edit-marketActivityName").val();
			var startDate = $("#edit-startDate").val();
			var endDate = $("#edit-endDate").val();
			var cost = $("#edit-cost").val();
			var description =$("#edit-description").val();
			//表单验证
			if(!formVerify(owner,name,startDate,endDate,cost)) {
				return;
			}
			$.ajax({
				url:"workbench/activity/saveEditActivity.do",
				data:{
					id,owner,name,startDate,endDate,cost,description
				},
				type:"post",
				dataType:"json",
				success:function(data){
					if(data.code == 1){
						//关闭修改市场的模态窗口
						$("#editActivityModal").modal("hide");
						//刷新市场活动列表,保持页号和每页显示条数都不变
						queryActivityByConditionForPage($("#demo_page1").bs_pagination('getOption','currentPage'),$("#demo_page1").bs_pagination('getOption','rowsPerPage'));
					}else {
						alert(data.message);
					}
				}
			});
		});

		//给”批量导出“按钮添加单击事件
		$("#exportActivityAllBtn").click(function(){
			//发送同步请求
			window.location.href = "workbench/activity/exportAllActivity.do";
		});

		//给”选择导出"按钮添加单击事件
		$("#exportActivityXzBtn").click(function(){
			//获取所有选中的checkbox
			let checkBoxs = $("#tBody input[type='checkbox']:checked");
			if(checkBoxs.size() < 1) {
				alert("至少选中一条数据进行导出！！！");
				return;
			}
			var ids="";
			$.each(checkBoxs,function(){
				ids += "id=" + this.value + "&"
			});
			ids = ids.substring(0,ids.length-1);
			window.location.href="workbench/activity/exportSelectedActivity.do?"+ids;
		});

		//给"导入“按钮添加单击事件
		$("#importActivityBtn").click(function(){
			var activityFileName = $("#activityFile").val();
			var suffix = activityFileName.substring(activityFileName.lastIndexOf(".")+1).toLowerCase();
			//表单验证
			if(suffix != "xls"){
				alert("只支持xls文件");
				return;
			}
			var activityFile = $("#activityFile")[0].files[0];
			if(activityFile > 5*1024*1024) {
				alert("文件不可大于5M");
				return;
			}

			//FormData是ajax提供的接口，可以模拟键值对向后台提交参数；
			//FormData最大的优势：不但能提交文本数据，还能提交二进制数据；
			var formData = new FormData();
			formData.append("activityFile",activityFile);
			//发送请求
			$.ajax({
				url:"workbench/activity/importActivity.do",
				data:formData,
				processData:false,//设置ajax向后台提交参数之前，是否将参数同一转成字符串,默认是true
				contentType:false,//是否把所有参数统一按urlencoded编码，默认是true
				type:"post",
				dataType:"json",
				success:function(data){
					if(data.code == 1) {
						alert(data.retObj);
						$("#importActivityModal").modal("hide");
						queryActivityByConditionForPage(1,$("#demo_page1").bs_pagination('getOption','rowsPerPage'))
					}else {
						alert(data.message)
					}
				}
			});
		});

	});
	//表单验证
	function formVerify(owner,name,startDate,endDate,cost) {
		if(owner == "" || name == ""){
			alert("所有者或者名称不能为空");
			return 0;
		}

		//验证日期是否符合需求
		if(startDate !="" && endDate !="") {
			//使用字符串的大小代替日期的大小
			if(startDate > endDate){
				alert("结束日期不可比开始日期小");
				return 0;
			}
		}

		//验证成本只能为非负整数
		var regExp = /^(([1-9]\d*)|0)$/
		if (!regExp.test(cost)) {
			alert("成本只能为非负整数");
			return 0;
		}
		return 1;
	}
	//定义分页查询函数
	function queryActivityByConditionForPage(pageNo,pageSize){
		//收集数据
		let name = $("#query-name").val();
		let owner = $("#query-owner").val();
		let startDate = $.trim($("#query-startDate").val());
		let endDate = $.trim($("#query-endDate").val());
		//发送ajax请求
		$.ajax({
			url:"workbench/activity/queryActivityByConditionForPage.do",
			data:{
				name,owner,startDate,endDate,pageNo,pageSize
			},
			type:"post",
			dataType: "json",
			success:function (data){
				//显示数据总条数
				// $("#recordB").html(data.totalRows);
				//显示市场活动列表
				//遍历activityList，拼接所有数据
				let htmlStr = "";
				$.each(data.activityList,function(index,obj) {
					htmlStr+="<tr class=\"active\">"
					htmlStr+="<td><input type=\"checkbox\" value=\""+obj.id+"\"/></td>"
					htmlStr+="<td><a style=\"text-decoration: none; cursor: pointer;\" onclick=\"window.location.href='workbench/activity/detailActivity.do?id="+ obj.id+"'\">"+obj.name+"</a></td>"
					htmlStr+="<td>"+obj.owner+"</td>"
					htmlStr+="<td>"+obj.startDate+"</td>"
					htmlStr+="<td>"+obj.endDate+"</td>"
					htmlStr+="</tr>"
				});
				$("#tBody").html(htmlStr);
				//每次渲染时，使"全选"按钮不选中
				$("#checkAll").prop("checked",false);
				//计算总页数
				var totalPages = data.totalRows % pageSize == 0 ? data.totalRows/pageSize:parseInt(data.totalRows/pageSize)+1;
				//bs_pagination翻页插件
				$("#demo_page1").bs_pagination({
					currentPage: pageNo,//当前页号,相当于pageNo
					rowsPerPage: pageSize,//每页显示条数，相当于pageSize
					totalRows: data.totalRows,//总条数
					totalPages: totalPages,//总页数

					visiblePageLinks: 5,//最多可以显示的卡片数

					showGoToPage: true,//是否显示“跳转到”部分，默认true--显示
					showRowsPerPate: true,//是否显示“每页显示条数”部分，默认true--显示
					showRowsInfo: true,//是否显示记录的信息，默认true--显示
					onChangePage:function(event,pageObj){
						queryActivityByConditionForPage(pageObj.currentPage,pageObj.rowsPerPage);
					}
				});
			}
		});

	}
</script>
</head>
<body>

	<!-- 创建市场活动的模态窗口 -->
	<div class="modal fade" id="createActivityModal" role="dialog">
		<div class="modal-dialog" role="document" style="width: 85%;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">×</span>
					</button>
					<h4 class="modal-title" id="myModalLabel1">创建市场活动</h4>
				</div>
				<div class="modal-body">

					<form id="createActivityForm" class="form-horizontal" role="form">

						<div class="form-group">
							<label for="create-marketActivityOwner" class="col-sm-2 control-label">所有者<span style="font-size: 15px; color: red;">*</span></label>
							<div class="col-sm-10" style="width: 300px;">
								<select class="form-control" id="create-marketActivityOwner">
									<c:forEach items="${userList}" var="user">
										<option value="${user.id}">${user.name}</option>
									</c:forEach>
								</select>
							</div>
                            <label for="create-marketActivityName" class="col-sm-2 control-label">名称<span style="font-size: 15px; color: red;">*</span></label>
                            <div class="col-sm-10" style="width: 300px;">
                                <input type="text" class="form-control" id="create-marketActivityName">
                            </div>
						</div>

						<div class="form-group">
							<label for="create-startDate" class="col-sm-2 control-label">开始日期</label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control mydate" id="create-startDate" readonly>
							</div>
							<label for="create-endDate" class="col-sm-2 control-label">结束日期</label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control mydate" id="create-endDate" readonly>
							</div>
						</div>
                        <div class="form-group">

                            <label for="create-cost" class="col-sm-2 control-label">成本</label>
                            <div class="col-sm-10" style="width: 300px;">
                                <input type="text" class="form-control" id="create-cost">
                            </div>
                        </div>
						<div class="form-group">
							<label for="create-describe" class="col-sm-2 control-label">描述</label>
							<div class="col-sm-10" style="width: 81%;">
								<textarea class="form-control" rows="3" id="create-describe"></textarea>
							</div>
						</div>

					</form>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="saveCreateActivityBtn">保存</button>
				</div>
			</div>
		</div>
	</div>

	<!-- 修改市场活动的模态窗口 -->
	<div class="modal fade" id="editActivityModal" role="dialog">
		<div class="modal-dialog" role="document" style="width: 85%;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">×</span>
					</button>
					<h4 class="modal-title" id="myModalLabel2">修改市场活动</h4>
				</div>
				<div class="modal-body">

					<form class="form-horizontal" role="form">
						<input type="hidden" id="edit-id">
						<div class="form-group">
							<label for="edit-marketActivityOwner" class="col-sm-2 control-label">所有者<span style="font-size: 15px; color: red;">*</span></label>
							<div class="col-sm-10" style="width: 300px;">
								<select class="form-control" id="edit-marketActivityOwner">
									<c:forEach items="${userList}" var="user">
										<option value="${user.id}">${user.name}</option>
									</c:forEach>
								</select>
							</div>
                            <label for="edit-marketActivityName" class="col-sm-2 control-label">名称<span style="font-size: 15px; color: red;">*</span></label>
                            <div class="col-sm-10" style="width: 300px;">
                                <input type="text" class="form-control" id="edit-marketActivityName" >
                            </div>
						</div>

						<div class="form-group">
							<label for="edit-startDate" class="col-sm-2 control-label ">开始日期</label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control mydate" id="edit-startDate" readonly >
							</div>
							<label for="edit-endDate" class="col-sm-2 control-label mydate">结束日期</label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control mydate" id="edit-endDate" readonly >
							</div>
						</div>

						<div class="form-group">
							<label for="edit-cost" class="col-sm-2 control-label">成本</label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control" id="edit-cost" >
							</div>
						</div>

						<div class="form-group">
							<label for="edit-description" class="col-sm-2 control-label">描述</label>
							<div class="col-sm-10" style="width: 81%;">
								<textarea class="form-control" rows="3" id="edit-description"></textarea>
							</div>
						</div>

					</form>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default"  data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="updateActivityBtn">更新</button>
				</div>
			</div>
		</div>
	</div>

	<!-- 导入市场活动的模态窗口 -->
    <div class="modal fade" id="importActivityModal" role="dialog">
        <div class="modal-dialog" role="document" style="width: 85%;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">×</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel">导入市场活动</h4>
                </div>
                <div class="modal-body" style="height: 350px;">
                    <div style="position: relative;top: 20px; left: 50px;">
                        请选择要上传的文件：<small style="color: gray;">[仅支持.xls]</small>
                    </div>
                    <div style="position: relative;top: 40px; left: 50px;">
                        <input type="file" id="activityFile">
                    </div>
                    <div style="position: relative; width: 400px; height: 320px; left: 45% ; top: -40px;" >
                        <h3>重要提示</h3>
                        <ul>
                            <li>操作仅针对Excel，仅支持后缀名为XLS的文件。</li>
                            <li>给定文件的第一行将视为字段名。</li>
                            <li>请确认您的文件大小不超过5MB。</li>
                            <li>日期值以文本形式保存，必须符合yyyy-MM-dd格式。</li>
                            <li>日期时间以文本形式保存，必须符合yyyy-MM-dd HH:mm:ss的格式。</li>
                            <li>默认情况下，字符编码是UTF-8 (统一码)，请确保您导入的文件使用的是正确的字符编码方式。</li>
                            <li>建议您在导入真实数据之前用测试文件测试文件导入功能。</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="importActivityBtn" type="button" class="btn btn-primary">导入</button>
                </div>
            </div>
        </div>
    </div>


	<div>
		<div style="position: relative; left: 10px; top: -10px;">
			<div class="page-header">
				<h3>市场活动列表</h3>
			</div>
		</div>
	</div>
	<div style="position: relative; top: -20px; left: 0px; width: 100%; height: 100%;">
		<div style="width: 100%; position: absolute;top: 5px; left: 10px;">

			<div class="btn-toolbar" role="toolbar" style="height: 80px;">
				<form class="form-inline" role="form" style="position: relative;top: 8%; left: 5px;">

				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">名称</div>
				      <input class="form-control" type="text" id="query-name">
				    </div>
				  </div>

				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">所有者</div>
				      <input class="form-control" type="text" id="query-owner">
				    </div>
				  </div>


				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">开始日期</div>
					  <input class="form-control mydate" type="text" id="query-startDate" readonly />
				    </div>
				  </div>
				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">结束日期</div>
					  <input class="form-control mydate" type="text" id="query-endDate" readonly>
				    </div>
				  </div>

				  <button type="button" class="btn btn-default" id="queryActivityBtn">查询</button>

				</form>
			</div>
			<div class="btn-toolbar" role="toolbar" style="background-color: #F7F7F7; height: 50px; position: relative;top: 5px;">
				<div class="btn-group" style="position: relative; top: 18%;">
				  <button type="button" class="btn btn-primary" id="createActivityBtn"><span class="glyphicon glyphicon-plus"></span> 创建</button>
				  <button type="button" class="btn btn-default" id="modifyActivityBtn"><span class="glyphicon glyphicon-pencil"></span> 修改</button>
				  <button type="button" class="btn btn-danger" id="deleteActivityBtn"><span class="glyphicon glyphicon-minus"></span> 删除</button>
				</div>
				<div class="btn-group" style="position: relative; top: 18%;">
                    <button type="button" class="btn btn-default" id="importFileActivityBtn" data-toggle="modal" data-target="#importActivityModal" ><span class="glyphicon glyphicon-import"></span> 上传列表数据（导入）</button>
                    <button id="exportActivityAllBtn" type="button" class="btn btn-default"><span class="glyphicon glyphicon-export"></span> 下载列表数据（批量导出）</button>
                    <button id="exportActivityXzBtn" type="button" class="btn btn-default"><span class="glyphicon glyphicon-export"></span> 下载列表数据（选择导出）</button>
                </div>
			</div>
			<div style="position: relative;top: 10px;">
				<table class="table table-hover">
					<thead>
						<tr style="color: #B3B3B3;">
							<td><input type="checkbox" id="checkAll"/></td>
							<td>名称</td>
                            <td>所有者</td>
							<td>开始日期</td>
							<td>结束日期</td>
						</tr>
					</thead>
					<tbody id="tBody">

					</tbody>
				</table>
			</div>
			<%--使用bs_pagination插件--%>
			<div class="col-md-12" id="demo_page1"></div>
			<%--<div style="height: 50px; position: relative;top: 30px;">
				<div>
					<button type="button" class="btn btn-default" style="cursor: default;">共<b id="recordB">50</b>条记录</button>
				</div>
				<div class="btn-group" style="position: relative;top: -34px; left: 110px;">
					<button type="button" class="btn btn-default" style="cursor: default;">显示</button>
					<div class="btn-group">
						<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
							10
							<span class="caret"></span>
						</button>
						<ul class="dropdown-menu" role="menu">
							<li><a href="#">20</a></li>
							<li><a href="#">30</a></li>
						</ul>
					</div>
					<button type="button" class="btn btn-default" style="cursor: default;">条/页</button>
				</div>
				<div style="position: relative;top: -88px; left: 285px;">
					<nav>
						<ul class="pagination">
							<li class="disabled"><a href="#">首页</a></li>
							<li class="disabled"><a href="#">上一页</a></li>
							<li class="active"><a href="#">1</a></li>
							<li><a href="#">2</a></li>
							<li><a href="#">3</a></li>
							<li><a href="#">4</a></li>
							<li><a href="#">5</a></li>
							<li><a href="#">下一页</a></li>
							<li class="disabled"><a href="#">末页</a></li>
						</ul>
					</nav>
				</div>
			</div>--%>

		</div>

	</div>
</body>
</html>
